package com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30;

import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.message.CMPP3Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CMPP3StreamEncoder extends MessageToByteEncoder<CMPP3Message> {

    private static final Logger logger = LoggerFactory.getLogger(CMPP3StreamEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext context, CMPP3Message message, ByteBuf buff) throws Exception {
        try {
            //消息长度
            int size = 0;
            size = message.encode(buff);

            //校正消息体长度
            message.setTotalLength(size);
            buff.setInt(0, size);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            logger.error("编码消息:" + message.toString());
            buff.clear();
            logger.debug("ENCODE: " + ByteBufUtil.prettyHexDump(buff));
        }

    }
}
